package headfirst.observer;
import java.util.ArrayList;
import java.lang.String;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

class LogReader implements IntfSubject
{
	private ArrayList<IntfObserver> m_oblist = null;
	private String[] m_infread = null;
	
	public LogReader()
	{
		this.m_oblist  = new ArrayList<IntfObserver>();
	}

	public boolean registerOberserver(IntfObserver tmpob)
	{
		if(null == tmpob)
		{
			return false;
		}
		if(!(tmpob instanceof IntfObserver))
		{
			return false;
		}
		System.out.println("in registerOberserver do add");
		this.m_oblist.add(tmpob);	
		return true;
	}

	public boolean removeObserver(IntfObserver tmpob)
	{
		if(null == tmpob)
		{
			return false;
		}
		int index = this.m_oblist.indexOf(tmpob);
		if(index >= 0)
		{
			System.out.println("in removeObserver do remove");
			this.m_oblist.remove(tmpob);
		}
		return false;
	}

	public boolean notifyObservers()
	{
		for(int i=0; i<this.m_oblist.size(); ++i)
		{
			IntfObserver theob = (IntfObserver)this.m_oblist.get(i);
			if(null != theob && theob instanceof IntfObserver)
			{
				theob.doUpdate(this.m_infread);
			}
		} 
		return true;
	}

	public boolean doReadFile(String filePath)
	{
		if(null==filePath)
		{
			return false;
		}
		File flog = new File(filePath);
		if(!flog.canRead())
		{
			return false;
		}
		
		System.out.println("in doReadFile, read log "+filePath);
		try 
		{
			FileReader fr = new FileReader(flog); 
			BufferedReader login = new BufferedReader(fr); 
			String line; 
			while ((line = login.readLine( )) != null) 
			{
				//System.out.println(line); 
				String[] tmpstrarr = line.split("\001");
				if(tmpstrarr.length>0)
				{
					this.m_infread = tmpstrarr;
					this.notifyObservers();
				}
			}
		} 
		catch (FileNotFoundException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return true;
	}
}
